//Oss上传类
import 'dart:io';

import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter_oss_aliyun/flutter_oss_aliyun.dart';
import 'package:qiniu_flutter_sdk/qiniu_flutter_sdk.dart';

class OssUpload {
  static int type = 0;

  static String aliyunOssKeyId = '';
  static String aliyunOssKeySecret = '';
  static String aliyunOssEndpoint = '';
  static String aliyunOssBucket = '';
  static String aliyunOssUrl = '';
  static String aliyunOssToken = '';

  OssUpload._();

  static Future<List<String>?> upoladFiles(List<File> fileList) async {
    List<String> result = [];
    final value = await Network.getOssConfig();

    print(' upoladFiles value  ==== $value');

    switch (value['code']) {
      case 'ali_oss':
        type = 1;
        aliyunOssKeyId = value['content']['oss_key_id'];
        aliyunOssKeySecret = value['content']['oss_key_secret'];
        aliyunOssEndpoint = value['content']['oss_endpoint'];
        aliyunOssBucket = value['content']['oss_bucket'];
        aliyunOssUrl = value['content']['url'];
        aliyunOssToken = value['token'];
        Client.init(
          ossEndpoint: aliyunOssEndpoint,
          bucketName: aliyunOssBucket,
          authGetter: () {
            return Auth(accessKey: aliyunOssKeyId, accessSecret: aliyunOssKeySecret, secureToken: aliyunOssToken, expire: '');
          },
        );
        List<AssetEntity> files = [];
        for (File file in fileList) {
          List<int> fileBytes = await file.readAsBytes();
          files.add(AssetEntity(
            filename: "bbc-channel-web/app/${Tools.getRandomString(8)}${file.path.split("/").last}",
            bytes: fileBytes,
            option: PutRequestOption(
              bucketName: aliyunOssBucket,
              aclModel: AclMode.publicRead,
            ),
          ));
        }
        List responses = await Client().putObjects(files);
        for (var response in responses) {
          result.add(response.realUri.toString());
        }

        return result;
      case 'qiniu_oss':
        Tools.hideLoading();
        type = 2;
        var token = value['token'];
        Map content = value['content'];
        String upLoadURL = content['upLoadURL'];

        final storage = Storage();
        // 开始上传文件
        List<String> uploadedUrls = await uploadFiles(fileList, token, upLoadURL);

        return uploadedUrls;

        break;

      default:
        print("类型错误");
    }
  }
}

// 上传文件并返回每个文件的上传结果（返回图片的 URL 地址数组）
Future<List<String>> uploadFiles(List<File> fileList, String token, String upLoadURL) async {
  final storage = Storage(); // 实例化 Storage 类

  // 存储每个上传任务的 Future
  List<Future> uploadFutures = [];
  List<String> uploadedFileUrls = []; // 存储上传成功后的图片 URL 地址

  // 遍历文件列表，创建上传任务
  for (File selectedFile in fileList) {
    uploadFutures.add(uploadFile(storage, selectedFile, token, uploadedFileUrls, upLoadURL));
  }

  // 使用 Future.wait 来并发上传所有文件，并等待所有任务完成
  try {
    // 等待所有文件上传任务完成
    await Future.wait(uploadFutures);

    // 如果没有抛出异常，所有文件上传成功
    print("All files uploaded successfully!");

    // 输出每个文件的 URL 地址
    uploadedFileUrls.forEach((url) {
      print('File uploaded and accessible at: $url');
    });

    return uploadedFileUrls; // 返回所有上传的图片 URL 地址
  } catch (e) {
    // 如果出现错误，捕获并打印错误信息
    print('Error occurred during upload: $e');
    return []; // 如果上传失败，返回空列表
  }
}

// 上传单个文件并返回上传结果
Future<void> uploadFile(Storage storage, File selectedFile, String token, List<String> uploadedFileUrls, String upLoadURL) async {
  try {
    // 上传文件
    final response = await storage.putFile(
      selectedFile,
      token,
      options: PutOptions(),
    );

    // 获取上传成功后的文件 key
    String fileKey = response.key!;

    // 构建文件的 URL 地址
    String fileUrl = '$upLoadURL/$fileKey';

    // 上传成功，添加到上传结果列表
    uploadedFileUrls.add(fileUrl);
    print('Uploaded ${selectedFile.path}, file accessible at: $fileUrl');
  } catch (e) {
    // 如果上传失败，抛出错误
    throw 'Failed to upload ${selectedFile.path}: $e';
  }
}
